package com.alfayun.fiscalriskanalysis.util;

import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import org.springframework.lang.NonNull;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

@Converter
public class TagsConverter implements AttributeConverter<Set<String>, String> {

	@NonNull
	@Override
	public String convertToDatabaseColumn(Set<String> tags) {
		return joinSet(tags);
	}

	@NonNull
	@Override
	public Set<String> convertToEntityAttribute(String tags) {
		return splitString(tags);
	}
	
	public static String joinSet(Set<String> tags) {
		if(tags != null) {
			return Joiner.on(',').join(tags);
		}
		return null;
	}

	public static Set<String> splitString(String tags) {
		if(tags != null) {
			return new TreeSet<>(Splitter.on(',').omitEmptyStrings().trimResults()
					.splitToList(tags).stream().map(it -> it).collect(Collectors.toSet()));
		}
		return null;
	}

}
